/**
 * Created by wangxin on 2017-9-26 10:02:01.
 */

'use strict';
console.log('enter。。。。');
console.log(111);
const page = {
    countNum: $('.countNum'),
    eventStart: $('.eventStart'),
    eventEnd: $('.eventEnd'),
    receiveDate: $('#receiveDate'),
    limit: $('#limit'),
    drawPrice: $('#drawPrice'),
    couponPrize: $('.couponPrize'),

    url: {
        loadEventRule: contextData.contextPath + '/work/loadEventRule',
        getResult: contextData.contextPath + '/work/getResult'
    },

    _id: null,
    list: null,
    currPoint: null,
    drawFlag: true,
    dateFlag: false,
    turnplate: {
        restaraunts: [],				//大转盘奖品名称
        colors: [],					//大转盘奖品区块对应背景颜色
        outsideRadius: 175,			//大转盘外圆的半径
        textRadius: 145,				//大转盘奖品位置距离圆心的距离
        insideRadius: 48,			//大转盘内圆的半径
        startAngle: 0,				//开始角度
        bRotate: false				//false:停止;ture:旋转
    }
};

page.init = function () {
    page.initElement();
    page.initEvent();
};

page.initElement = function () {
    const thisPage = this;
    thisPage.turnplate.restaraunts = ['谢谢参与'];
    thisPage.turnplate.hidden = ['谢谢参与'];
    Dolphin.ajax({
        url: thisPage.url.loadEventRule,
        type: "get",
        forceUrl: 'true',
        data: {eventId: contextData.data.eventId, gameType: 'plate'},
        // data: {eventId:'a17f5e06-561b-488f-9d31-e1364d817b4a'},
        onSuccess: function (data) {
            if (data && data.event) {
                $(document).attr("title", data.event.eventName);

                var createOrgCode = contextData.userData && contextData.userData.createOrgCode || null;
                var store = data && data.store || null;
                if(!(!createOrgCode || !store || (store && !store.length) || store.find(o=>o.code === createOrgCode))){
                if(!(!createOrgCode || !store || (store && !store.length) || store.find(o=>o.code === createOrgCode))){
                    var bg = $("<div style='position:fixed;top: 0;bottom:0;left:0;right:0;text-align: center;padding-top:90%;font-weight:700;color: white;font-size:24px;background: rgba(55,55,55,0.75)'>您不能参加本次活动" +
                        "<br />请咨询相关门店人员</div>");
                    $("body").append(bg);
                }


                var ruleList = data.rule;
                var today = new Date(),
                    eds = data.event.eventDateStart,
                    ede = data.event.eventDateEnd;
                thisPage.countNum.html(sessionStorage.getItem('currPoint') || contextData.userData.currPoint);

                if (data.event.limitNum === null) {
                    $('.curCount').html('不限')
                } else {
                    var remainNum = data.event.limitNum - data.count;
                    if (remainNum > 0) {
                        $('.curCount').html(remainNum);
                    } else {
                        $('.curCount').html(0);
                        thisPage.turnplate.bRotate = true;
                        alert('次数达到上限啦...等下次活动吧~')
                    }
                }

                thisPage.eventStart.html(thisPage.formatterDate(eds));
                thisPage.eventEnd.html(thisPage.formatterDate(ede));
                thisPage.receiveDate.html(thisPage.formatterDate(data.event.receiveDate));
                thisPage.limit.html(data.event.limitNum);
                if (today <= new Date(ede) && today >= new Date(eds)) {
                    page.dateFlag = true;
                }
                for (var i = 0; i < ruleList.length; i++) {
                    if (ruleList[i].prizeType === 'point') {
                        ruleList[i].prizeType = '积分';
                    } else if (ruleList[i].prizeType === 'coupon') {
                        ruleList[i].prizeType = '礼券';
                    } else if (ruleList[i].prizeType === 'prize') {
                        ruleList[i].prizeType = '实物';
                    }
                    thisPage.initRouletteWheel(i, ruleList[i]);
                }
                thisPage.finishDrawRouletteWheel(ruleList.length);
                $('#context').append(data.event.intro);
                new Vue({
                    el: '#ruleInfo',
                    data: {
                        rules: data.rule,
                        eventInfo: data.event.intro
                    },
                });
            }
        },
        onError: function (e) {
            alert('网络出错啦，请您重新加载');
        }
    });
};

page.initEvent = function () {
    const thisPage = this;
    var drawClick = function () {
        if (page.dateFlag) {
            if (thisPage.turnplate.bRotate) return;
            thisPage.turnplate.bRotate = !thisPage.turnplate.bRotate;
            Dolphin.ajax({
                url: thisPage.url.getResult,
                type: "get",
                async: false,
                forceUrl: 'true',
                data: {eventId: contextData.data.eventId, gameType: 'plate'},
                // data: {eventId: 'a17f5e06-561b-488f-9d31-e1364d817b4a'},
                onSuccess: function (data) {
                    console.log(data);
                    console.log(data);
                    if (data.err) {
                        alert(data.err);
                    } else {
                        if (data.result.limitNum === null) {
                            $('.curCount').html('不限');
                        } else {
                            var remainNum = (data.result.limitNum || data.result.eventId.limitNum) - data.count;
                            if (remainNum > 0) {
                                $('.curCount').html(remainNum);
                                thisPage.countNum.html(parseInt(data.addMsg.curUserPoint));
                                sessionStorage.setItem('currPoint', parseInt(data.addMsg.curUserPoint))
                            } else if (remainNum == 0) {
                                thisPage.drawFlag = false;
                                $('.curCount').html(0);
                            }
                        }
                        if (data.result.eventId) {
                            console.log(data);
                            thisPage.couponPrize.html(data.result.rule);
                            console.log(data.result.prizeType);
                            if (data.result.prizeType === 'point') {
                                $('.couponRight').html('获得积分:' + data.result.point + '分');
                            } else if (data.result.prizeType === 'prize') {
                                $('.couponRight').html(data.result.priceName);
                            } else {
                                $('.couponRight').html(data.result.giftName);
                            }
                            thisPage.rotateFn(thisPage.turnplate.hidden.indexOf(data.result._id) + 1, data.result.rule);
                        } else {
                            thisPage.rotateFn(1, 1);
                        }
                    }
                },
                onError: function (e) {
                    $.toast("网络出错啦，稍后为您重新加载:)", "text");
                }
            });
        } else {
            alert('亲~，现在不在活动期，尽情期待...')
        }
    }
    thisPage.drawPrice.click(drawClick);
    $('.closeModels').click(function () {
        $('.model').hide();
        $('.shadow').hide();
        drawClick();
    });
    $('.closeModel').click(function () {
        $('.model').hide();
        $('.shadow').hide();
    });
};

page.formatterDate = function (val, formatter) {
    if (val) {
        var date = Dolphin.string2date(val, "yyyy-MM-ddThh:mm:ss.");
        date.setHours(date.getHours() + 8);
        return Dolphin.date2string(date, formatter || "yyyy-MM-dd");
    } else {
        return '';
    }
};

page.initRouletteWheel = function (i, rule) {
    const thisPage = page;
    if (i % 2 == 0) {
        thisPage.turnplate.colors.push("#FFCA3E")
    } else {
        thisPage.turnplate.colors.push("#FFB822")
    }
    thisPage.turnplate.restaraunts.push(rule.rule);
    thisPage.turnplate.hidden.push(rule._id);
};

page.finishDrawRouletteWheel = function (n) {
    const thisPage = page;
    if (n == 3) {
        console.log(thisPage.turnplate.restaraunts);
        thisPage.turnplate.restaraunts.splice(Math.ceil(thisPage.turnplate.restaraunts.length / 2), 0, '谢谢参与');
        thisPage.turnplate.hidden.splice(Math.ceil(thisPage.turnplate.hidden.length / 2), 0, '谢谢参与');
        thisPage.turnplate.restaraunts.splice(Math.ceil(thisPage.turnplate.restaraunts.length / 2) + 1, 0, '谢谢参与');
        thisPage.turnplate.hidden.splice(Math.ceil(thisPage.turnplate.hidden.length / 2) + 1, 0, '谢谢参与');
        console.log(thisPage.turnplate.restaraunts);
        thisPage.turnplate.colors.push("#FFB822", "#FFCA3E", "#FFB822");
    } else {
        if (thisPage.turnplate.restaraunts.length % 2 != 0) {
            thisPage.turnplate.colors.push("#FFCA3E", "#FFB822");
            thisPage.turnplate.restaraunts.splice(Math.ceil(thisPage.turnplate.restaraunts.length / 2), 0, '谢谢参与');
            thisPage.turnplate.hidden.splice(Math.ceil(thisPage.turnplate.hidden.length / 2), 0, '谢谢参与');
        } else {
            thisPage.turnplate.colors.push("#FFB822")
        }
    }
    thisPage.drawRouletteWheel();
};

page.rotateFn = function (item, txt) {
    var angles = item * (360 / page.turnplate.restaraunts.length) - (360 / (page.turnplate.restaraunts.length * 2));
    if (angles < 270) {
        angles = 270 - angles;
    } else {
        angles = 360 - angles + 270;
    }
    $('#wheelcanvas').stopRotate();
    $('#wheelcanvas').rotate({
        angle: 0,
        animateTo: angles + 1800,
        duration: 8000,
        callback: function () {
            if (page.drawFlag) {
                page.turnplate.bRotate = !page.turnplate.bRotate;
            } else {
                page.turnplate.bRotate = true
            }
            if (txt == '1') {
                $.toptip('没中奖，运气不太好哦，>。<', 'error');
            } else {
                $('.shadow').show();
                $('.model').show();
            }
        }
    });
};

page.drawRouletteWheel = function () {
    var canvas = document.getElementById("wheelcanvas");
    if (canvas.getContext) {
        //根据奖品个数计算圆周角度
        var arc = Math.PI / (page.turnplate.restaraunts.length / 2);
        var ctx = canvas.getContext("2d");
        //在给定矩形内清空一个矩形
        ctx.clearRect(0, 0, 422, 422);
        //strokeStyle 属性设置或返回用于笔触的颜色、渐变或模式
        ctx.strokeStyle = "#881700";
        //font 属性设置或返回画布上文本内容的当前字体属性
        ctx.font = ' bold  22px  Microsoft YaHei  ';
        for (var i = 0; i < page.turnplate.restaraunts.length; i++) {
            var angle = page.turnplate.startAngle + i * arc;
            ctx.fillStyle = page.turnplate.colors[i];
            ctx.beginPath();
            //arc(x,y,r,起始角,结束角,绘制方向) 方法创建弧/曲线（用于创建圆或部分圆）
            ctx.arc(211, 211, page.turnplate.outsideRadius, angle, angle + arc, false);
            ctx.arc(211, 211, page.turnplate.insideRadius, angle + arc, angle, true);
            ctx.stroke();
            ctx.fill();
            //锁画布(为了保存之前的画布状态)
            ctx.save();

            //----绘制奖品开始----
            ctx.fillStyle = "#881700";
            var text = page.turnplate.restaraunts[i];
            var line_height = 17;
            //translate方法重新映射画布上的 (0,0) 位置
            ctx.translate(211 + Math.cos(angle + arc / 2) * page.turnplate.textRadius, 211 + Math.sin(angle + arc / 2) * page.turnplate.textRadius);

            //rotate方法旋转当前的绘图
            ctx.rotate(angle + arc / 2 + Math.PI / 2);

            /** 下面代码根据奖品类型、奖品名称长度渲染不同效果，如字体、颜色、图片效果。(具体根据实际情况改变) **/
            if (text.indexOf("M") > 0) {//流量包
                var texts = text.split("M");
                for (var j = 0; j < texts.length; j++) {
                    ctx.font = j == 0 ? 'bold 20px Microsoft YaHei' : '16px Microsoft YaHei';
                    if (j == 0) {
                        ctx.fillText(texts[j] + "M", -ctx.measureText(texts[j] + "M").width / 2, j * line_height);
                    } else {
                        ctx.fillText(texts[j], -ctx.measureText(texts[j]).width / 2, j * line_height);
                    }
                }
            } else if (text.indexOf("M") == -1 && text.length > 6) {//奖品名称长度超过一定范围
                text = text.substring(0, 6) + "||" + text.substring(6);
                var texts = text.split("||");
                for (var j = 0; j < texts.length; j++) {
                    ctx.fillText(texts[j], -ctx.measureText(texts[j]).width / 2, j * line_height);
                }
            } else {
                //在画布上绘制填色的文本。文本的默认颜色是黑色
                //measureText()方法返回包含一个对象，该对象包含以像素计的指定字体宽度
                ctx.fillText(text, -ctx.measureText(text).width / 2, 0);
            }

            //把当前画布返回（调整）到上一个save()状态之前
            ctx.restore();
            //----绘制奖品结束----
        }
    }
};

$(function () {
    page.init();
});




